/*
 * @Author: yixin 
 * @Date: 2019-11-20 15:51:30 
 * @Last Modified by: yixin
 * @Last Modified time: 2020-04-26 11:34:02
 * home
 */
import React, { Component } from "react"
import { withRouter } from "react-router"
import AMap from 'AMap'
import styles from './home.less'
import { homeStatistics, workState, projectCount, getAlarm } from '@/services'
import { formatDate, fetchProjectMap } from '@/utils'
import DatePicker from '@/components/datePicker'
import Statistics from '@/components/statistics'
import Time from '@/components/time'

const time_arr = [
  { name: '今天' },
  { name: '本月' },
  { name: '本年' },
  { name: '其他时间' },
]

class Home extends Component {

  constructor(props){
    super(props);
    this.state = {
      statistics: {},
      workState: {},
      projectCount: {},
      mapStatus: [], // 图标点状态
      isAlarm: false
    }
    this.times = {
      beginDate: formatDate(new Date()),
      endDate: formatDate(new Date())
    }
    sessionStorage.setItem('hometime',JSON.stringify(this.times));
  }

  handleChangeTab = (times) => {
    this.times = times;
    sessionStorage.setItem('hometime',JSON.stringify(this.times));
    this.getHomeStatistics()
  }

  componentDidMount () {
    this.map = new AMap.Map('map');
    this.getHomeStatistics();
    this.getWorkState();
    this.getProjectCount();
    // 工程数据预请求
    fetchProjectMap();
    // 获取警报信息
    this.fetchAlarm();
  }

  getHomeStatistics = async () => {
    try {
      const data = await homeStatistics(this.times)
      this.setState({
        statistics: data.data
      })
    } catch (error) {
      console.log(error)
    }
  }

  getWorkState = async() => {
    try {
      const data = await workState();
      this.setState({
        workState: data.data
      },this.renderMap)
    } catch (error) {
      console.log(error)
    }
  }

  getProjectCount = async() => {
    try {
      const data = await projectCount();
      this.setState({
        projectCount: data.data
      })
    } catch (error) {
      console.log(error)
    }
  }

  fetchAlarm = async () => {
    try {
      const data = await getAlarm({ equipCode: '', pageNo: 1, pageSize: 1 });
      this.setState({
        isAlarm: data.data.length>0
      })
    } catch (error) {
      console.log(error)
    }
  }
  

  renderIcon = (index) => {
    return `<div class=${this.state.mapStatus[index-1]==0 ? styles.icon : styles.icon_disabled}>
    ${index}
  </div>`
  }

  renderMap = () => {
    const point = []; //总数组
    const mapStatus = [];
    var marker;
    this.state.workState.equips && this.state.workState.equips.map((data, index)=>{
      if(data.location && data.location.longitude && data.location.latitude){
        point.push(new AMap.LngLat(data.location.longitude,data.location.latitude))
        mapStatus.push(this.state.workState.equips[index].state)
      } 
    })
    this.setState({ mapStatus })
    var polyline2;
    AMap.convertFrom(point, 'gps', (status, result) => {
      if (result.info === 'ok') {
        var lnglats = result.locations; // Array.<LngLat>
        lnglats.map(((data, index)=>{
          let marker = new AMap.Marker({
              position: data,   // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
              content: this.renderIcon(index+1)
          });
          this.map.add(marker);
        }))
        this.map.setFitView()
      }
    });
  }
  
  
  render(){
    const { active, statistics, workState, projectCount } = this.state;
    return (
      <div>
        <div className={styles.header}>
          <img className={styles.top_bg} src={require('../assets/img/home/top_bg.png')} />
          <div className={styles.content}>
            <div className={styles.header_left}>
              <div className={styles.header_title}>泵车管家</div>
              <div className={styles.header_time}>{this.times.beginDate===this.times.endDate ? this.times.beginDate : `${this.times.beginDate} / ${this.times.endDate}`}</div>
            </div>
            <div className={styles.header_right}>
              <img onClick={()=>{ this.props.history.push('myequip') }} className={styles.icon} src={require('../assets/img/home/add.png')} />
              <div className={styles.alarm_box}>
                <img onClick={()=>{ this.props.history.push('alarm') }} className={styles.icon} src={require('../assets/img/home/alarm.png')} />
                <div className={styles.alarm_red}></div>
              </div>
              <img onClick={()=>{ this.props.history.push('statistics') }} className={styles.icon} src={require('../assets/img/home/statistics.png')} />
              <img onClick={()=>{ this.props.history.push('login') }} className={styles.icon} src={require('../assets/img/home/exit.png')} />
            </div>
          </div>
        </div>
        <div className={styles.container}>
          {/* {(this.datePicker && this.datePicker.getActive() == 3) && <Time time={this.times.beginDate===this.times.endDate ? this.times.beginDate : `${this.times.beginDate} / ${this.times.endDate}`} />} */}
          <DatePicker ref={(el) => this.datePicker = el} defaultTime={this.times} handleChangeTab={this.handleChangeTab} />
          <Statistics times={this.times} statistics={statistics} />
          <div className={styles.menu}>
            <div className={styles.menu_car} onClick={()=>this.props.history.push('/carlist',{ worktime: this.times })}>
              <div className={styles.menu_content}>
                <div className={styles.menu_name}>车辆</div>
                <div className={styles.menu_value}>全部 {workState.totalEquipNum||0}&nbsp;&nbsp;在线 {workState.onlineEquipNum||0}</div>
              </div>
            </div>
            <div className={styles.menu_project} onClick={()=>this.props.history.push('/projectlist',{ worktime: this.times })}>
              <div className={styles.menu_project}>
              <div className={styles.menu_content}>
                <div className={styles.menu_name}>工程</div>
                <div className={styles.menu_value}>全部 {projectCount.totalProjectNum||0}&nbsp;&nbsp;施工 {projectCount.onlineProjectNum||0}</div>
              </div>
              </div>
            </div>
          </div>
          <div id="map" className={styles.map} onClick={() => { this.props.history.push('carlist') }}>
            
          </div>
        </div>
      </div>
    )
  }
}

export default withRouter(Home)